"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

from mod_python import apache
from mod_python import Session
from mod_python import util
import psycopg2

from phunc import *
import phunc.cx_wrapper.db_tools as db_tools
from phunc.logger import logger

# legacy namespacing
GeneralBusinessErr = exception.GeneralBusinessErr
genErrorPage = error.genErrorPage

def user_exists(cursor, name):
	"""
	Checks if user exists
	Returns a boolean
	"""
	return len(db_tools.exec_action(cursor, 'app_get_user_info',[name])) > 0
	
def passwd_is_match(cursor, name, input_passwd):
	"""
	Checks password against encrypted password in database
	Returns a boolean
	"""
	return len(db_tools.exec_action(cursor, 'app_verify_user_passwd',[name,input_passwd])) > 0
#**************************************************page function start**************************************************
def index(req, **params):
	"""Authenticate user, save session, redirect to post-login page"""
	try:
		session = Session.Session(req,timeout=info.session_timeout)
		cursor = get_app_connection().cursor()
		if not user_exists(cursor, params['user_name']):
			raise GeneralBusinessErr('user_not_exist','/bin/login.py/login_out')
		else:
			user_info = db_tools.exec_action(cursor, 'app_get_user_info',[params['user_name']])[0]
			if not passwd_is_match(cursor, user_info['name'], params['user_password']):
				raise GeneralBusinessErr('error_password','/bin/login.py/login_out')
			else:
				session['login_user_id'] = user_info['id']
				session['login_user_name'] = params['user_name']
				session['skin'] = user_info['skin']
				session['portal_order'] = tuple(user_info['role_id'] or {})
				session.save()
				util.redirect(req, '/bin/root.py/loginpage')
	except GeneralBusinessErr,e:
		return genErrorPage(errmsg='%s'%e.getErrMsg(),errurl=e.getURL())
	except Exception,e:
		return genErrorPage( errmsg = "%s" % e.args )
	except:
		return genErrorPage()
		
def login_out(req,**params):
	"""deletes the current user session, redirects to login form"""
	try:
		session = Session.Session(req)
		session.delete()
		util.redirect(req,'/index.html?flag=1')
	except:
		return genErrorPage()
